/*
 * Copyright (c) 2010 Andy Aspell-Clark
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package uk.org.aspellclark.agenedb.view;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import uk.org.aspellclark.agenedb.AGeneDb;
import uk.org.aspellclark.agenedb.R;
import uk.org.aspellclark.agenedb.db.DatabaseObjectContainer;
import uk.org.aspellclark.agenedb.gedcom.Gedcom;
import uk.org.aspellclark.agenedb.gedcom.model.Individual;
import uk.org.aspellclark.agenedb.gedcom.model.IndividualEvent;
import uk.org.aspellclark.agenedb.gedcom.model.Multimedia;
import uk.org.aspellclark.agenedb.view.individual.IndividualChildrenListRowAdapter;
import uk.org.aspellclark.agenedb.view.individual.IndividualEventListRowAdapter;
import uk.org.aspellclark.common.ImageFunctions;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class IndividualDetailsView extends Activity implements OnClickListener {

	@Override
	public void onClick(View arg0) {
		Intent intnt = new Intent(this.getBaseContext(), GedcomTreeView.class);
		this.startActivity(intnt);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.individual_details_view);

		Button btnShowTree = (Button) this.findViewById(R.id.individualDetailsViewBtnShowTree);
		btnShowTree.setOnClickListener(this);

		this.updateIndividualDetails();
	}

	private void updateIndividualDetails() {
		try {
			Individual indiv = DatabaseObjectContainer.individualCntrlr
					.getIndividual(DatabaseObjectContainer.individualCntrlr.getCurrentPrsnId());

			if (indiv != null) {
				TextView firstnameVw = (TextView) this.findViewById(R.id.txtFirstNames);
				firstnameVw.setText(indiv.getNameFirst());

				TextView lastnameVw = (TextView) this.findViewById(R.id.txtLastNames);
				lastnameVw.setText("/" + indiv.getNameLast() + "/");

				TextView dobVw = (TextView) this.findViewById(R.id.txtDateBirth);
				dobVw.setText("Born: " + indiv.getDOB());

				TextView dodVw = (TextView) this.findViewById(R.id.txtDateDeath);
				dodVw.setText("Died: " + indiv.getDOD());

				TextView addrVw = (TextView) this.findViewById(R.id.txtIndividualAddress);
				addrVw.setText(indiv.address.toString());

				TextView genderVw = (TextView) this.findViewById(R.id.txtIndividualGender);
				if (indiv.sex != null && indiv.sex.equalsIgnoreCase("M")) {
					genderVw.setText("Male");
				} else if (indiv.sex != null && indiv.sex.equalsIgnoreCase("F")) {
					genderVw.setText("Female");
				} else {
					genderVw.setText("Unknown");
				}

				this.updateIndividualDetailsEvents(indiv);
				this.updateIndividualDetailsChildren(indiv);
				//this.updateIndividualDetailsMedia(indiv);
			}
		} catch (Exception e) {
			String errMsg = e.getMessage();
			//Toast.makeText(this, "Exception Caught populating Person Details", Toast.LENGTH_SHORT).show();
		}
	}

	private void updateIndividualDetailsChildren(Individual indiv) {

		ListView lstChildren = (ListView) this.findViewById(R.id.layoutIndividualChildrenList);
		ArrayList<String> childrenIds = new ArrayList<String>(Gedcom.getInstance().getChildren(indiv));

		IndividualChildrenListRowAdapter indivEvntAdapter = new IndividualChildrenListRowAdapter(this,
				R.layout.individual_event_list_view_row, childrenIds);

		//FIXME : indivEvntAdapter.sort(comparator);
		lstChildren.setAdapter(indivEvntAdapter);
		indivEvntAdapter.notifyDataSetChanged();

		lstChildren.requestLayout();
	}

	private void updateIndividualDetailsEvents(Individual indiv) {

		ListView lstEvents = (ListView) this.findViewById(R.id.layoutIndividualEventsList);
		ArrayList<IndividualEvent> eventList = new ArrayList<IndividualEvent>(indiv.events);

		IndividualEventListRowAdapter indivEvntAdapter = new IndividualEventListRowAdapter(this,
				R.layout.individual_event_list_view_row, eventList);

		//FIXME : indivEvntAdapter.sort(comparator);
		lstEvents.setAdapter(indivEvntAdapter);
		indivEvntAdapter.notifyDataSetChanged();

		lstEvents.requestLayout();
	}

	private void updateIndividualDetailsMedia(Individual indiv) {

		List<Multimedia> mediaList = indiv.multimedia;
		ImageView indivPictVw = (ImageView) this.findViewById(R.id.layoutIndividualImgVwPicture);

		//--------------------------
		Bitmap bmp = null;
		if (mediaList.size() > 0) {
			//set the image from the first multimedia item
			Multimedia mm = mediaList.get(0);
			if (mm.fileReference != null && mm.fileReference.length() > 0) {
				File tmpf = new File(mm.fileReference);
				String newFilename = AGeneDb.getGedomImagePathDir() + tmpf.getName();
				try {
					bmp = ImageFunctions.getImage(newFilename);
					if (bmp == null) {
						bmp = ImageFunctions.getImage(AGeneDb.getGedomPathDir() + tmpf.getName());
					}
				} catch (Throwable e) {
					String errMsg = e.getMessage();
				}
			}
		} else {
			bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.unknown_prsn);
		}
		if (bmp == null) {
			bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.unknown_prsn);
		}
		indivPictVw.setImageDrawable(new BitmapDrawable(ImageFunctions.scaleImage(bmp, 48)));
		//------------------------

		Gallery galleryVw = (Gallery) this.findViewById(R.id.galleryPictures);
		for (int x = 0; x < mediaList.size(); x++) {
			Multimedia mm = mediaList.get(x);
			ImageView img = new ImageView(this);
			try {
				if (mm.fileReference != null && mm.fileReference.length() > 0) {
					File tmpf = new File(mm.fileReference);
					String newFilename = AGeneDb.getGedomImagePathDir() + tmpf.getName();
					tmpf = new File(newFilename);
					if (tmpf.exists()) {
						bmp = new BitmapDrawable(newFilename).getBitmap();
					} else {
						newFilename = AGeneDb.getGedomPathDir() + tmpf.getName();
						tmpf = new File(newFilename);
						if (tmpf.exists()) {
							bmp = new BitmapDrawable(newFilename).getBitmap();
						}
					}
				}
			} catch (Exception e) {
				String errMsg = e.getMessage();
				//Toast.makeText(this, "Exception Caught updating individual media", Toast.LENGTH_SHORT).show();
			}
		}
		galleryVw.setFadingEdgeLength(40);

	}

}